package com.saikei.demoapp.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil.setContentView
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import java.lang.reflect.ParameterizedType

open class BaseVMFragment<VB : ViewDataBinding, VM : BaseInitVM> : Fragment() {

    protected lateinit var mBinding: VB
    protected lateinit var mViewModel: VM

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mBinding = createBinding(inflater,container)
        mViewModel = createViewModel()
        onFragmentCreate()
        return mBinding.root
    }

    private fun createBinding(inflater: LayoutInflater, container: ViewGroup?): VB {
        val type = (this::class.java.genericSuperclass as ParameterizedType).actualTypeArguments[0]
        val clazz = type as Class<VB>
        val method = clazz.getMethod("inflate", LayoutInflater::class.java, ViewGroup::class.java, Boolean::class.java)
        @Suppress("UNCHECKED_CAST")
        return method.invoke(null, inflater, container, false) as VB
    }

    protected open fun createViewModel(): VM {
        val type = (this::class.java.genericSuperclass as ParameterizedType).actualTypeArguments[1]
        val clazz = type as Class<VM>
        val application = requireActivity().application
        val factory = BaseInitVM.factory<VM>(app = application, clazz = clazz)
        return ViewModelProvider(this, factory)[clazz]
    }

    open fun onFragmentCreate(){}

}